// JavaScript Document

var pages = {

	contentType : 'html',
	pageListExpanded : false,
	ajax_page: 'ajax_pages/pages.php',
	
	init: function() {
		
        //$p.supports_back_button = true;
        
		// attach the folder expansion and contraction handles and link event listeners
		pages.attachFolderHandlers();
		
		
		/**
		 * Bind the binds for all the various items on the page
		 */
		$p("#checkall").bind("click",function() {
			var chkd = this.checked;
			$p.all(".cms-page-list li input[type=checkbox]", function(el) {
				el.checked = chkd;
			});	
		});
		
		$p("#add-page-link").bind('click',function() {
			
			var query = "action=load_parent_page_options";
			$p.post( pages.ajax_page, query, function(data) {
				
				document.getElementById("ParentID").innerHTML = data;
				
				$p(".newsTbl").css('display','none');
				$p(".editor-block").css('display','block');
				$p("#action").val("add_page");
				$p("#PageAddForm #submit-btn").val("Add Page");	
			});
			
		});
		
		$p("#delete-selected-link").bind('click',function() {
			var boxes = $p.all(".cms-page-list input[type=checkbox]");
			var selected = [];
			for( var i = 0, j = 0; i < boxes.length; i++ ) {
				if( boxes[i].checked ) {
					selected[j++] = boxes[i].value;
				}	
			}
			
			if( selected.length == 0 ) {
				alert("Please Select Pages To Delete Before Using This Option");
				return;
			}
			
			$p.showDialog({
				title: 'Confirm Delete Of Page and Sub Pages',
				content: 'Deleting this page will potentially delete all sub pages as well.<br />'
						+ 'Do you want to continue the process?',
				
				okButtonText: "Delete Page(s)",
				okButtonAction: function() {
					var query = "action=delete_pages&ids=" + selected;
					$p.post("ajax_pages/pages.php", query, function(data) {
						for( var i = 0; i < selected.length; i++ ) {
							$p("#page-li-" + selected[i]).remove();
                            pages.attachFolderHandlers();
						}
					});
				}
			});
		});
		
		// configure the home page content editor links
		$p(".edit-home-link").bind('click',function() {
			
			var query = "action=load_homepage";
			$p.post( pages.ajax_page, query, function(data) {
				$p.showDialog({
					title: 'Edit Home Page Text Content',
					content: data,
					width: '800px',
					okButtonText: 'Save Changes',
					okButtonAction: function() {
						// prepare content
						pages.prepHomePageContentForSubmit();
						
						// build query
						var query = "action=update_homepage&" + $p("#home_page_form").serialize();
						
						// submit form and close dialog
						$p.post(pages.ajax_page,query, function(d) {
							$p.hideDialog();	
						});
					}
				}, 
				
				function() {
					pages.initHomePageTabs();		
				});
			});
		});
		
		// configure the footer content editor links
		$p(".edit-footer-link").bind('click',function() {
			
			var query = "action=load_footer";
			$p.post( pages.ajax_page, query, function(data) {
				$p.showDialog({
					title: 'Edit Footer Text Content',
					content: data,
					width: '800px',
					okButtonText: 'Save Changes',
					okButtonAction: function() {
						// prepare content
						pages.prepHomePageContentForSubmit();
						
						// build query
						var query = "action=update_footer&" + $p("#page_footer_form").serialize();
						
						// submit form and close dialog
						$p.post(pages.ajax_page, query, function() {
							$p.hideDialog();	
						});
					}
				}, 
				
				function() {
					pages.initHomePageTabs();		
				});
			});
		});
		
			
			
		// initiate the tabs
		pages.$tabs = $("#page-tabs").tabs({
			select: function(ev,ui) {
				// cache the selected content type
				pages.contentType = "html";
				
				if( ui.panel.id == "php-pane" ) {
					pages.contentType = "php";
				}
			}	
		});
		
		if( document.getElementById("ContentType") ) {
			if( $("#ContentType").val() == "php" ) {
				pages.$tabs.tabs('select',1);
			}
		}
		
		// make the Page Title field have an sef url version
		if( document.getElementById("id").value == "" ) {
			$("#PageName").friendurl({id: 'PageNameAlias'});
		}
		
		// make the HTMLContent TextArea an HTML Editor
		ui.htmlSummaryEditor("PageSummary");
		
		// make the HTMLContent TextArea an HTML Editor
		ui.htmlContentEditor("HTMLContent");
		
		// setup the callback for the form editor form to use
		$p(".PagesForm").node().onsubmit = function() {
			pages.prepContentForSubmit();
			return false;
		};
		
		$p("#PageAddForm #cancel-btn").bind('click',function() {
			$p.showConfirmMessage({
				title: 'Confirm Process Cancelation',
				content: 'Do you want to cancel the current page editing process?',
				okButtonText: 'Yes',
				cancelButtonText: 'No',
				okButtonAction: function() {
					$p(".newsTbl").css('display','table');
					$p(".editor-block").css('display','none');
					
					document.getElementById("PageAddForm").reset();	
				} 	
			});
		});
		
		$p("#PageAddForm #submit-btn").bind('click', function() {
			pages.processFormData();
		});
		
	},
	
	/**
	 * Sorts the pages tree so the pages are displayed in the order specified by
	 * the user. Also sorts the pages list of the items in the ParentID combo box
	 * based on the new page order
	 */
	sortPages: function(parent_node) {

		var items = parent_node.childNodes;
		var itemsArr = [];
		for (var i in items) {
			if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
				itemsArr.push(items[i]);
			}
		}
		
		itemsArr.sort(function(a, b) {
		  return a.getAttribute("data-position") == b.getAttribute("data-position")
				  ? 0
				  : (a.getAttribute("data-position") > b.getAttribute("data-position") ? 1 : -1);
		});
		
		for (i = 0; i < itemsArr.length; ++i) {
		  parent_node.appendChild(itemsArr[i]);
		}
	},
	
	initHomePageTabs: function() {
		// home page editing
		if( document.getElementById("home-page-tabs")) {
			// make tabs
			$("#home-page-tabs").tabs({
				select: function(ev,ui) {
					// cache the selected content type
					pages.contentType = "html";
					
					if( ui.panel.id == "php-pane" ) {
	                    pages.contentType = "php";
					}
				}	
			});

			
			// make editor
			if( document.getElementById("SiteHomePageText") ){
				ui.htmlContentEditor("BlockContent");
				
			} else if( document.getElementById("SiteFooterText") ) {
				// make editor for footer
				ui.htmlContentEditor("BlockContent");
			}
			
			
			// setup the callback for the form editor form to use
            var pageForm = $p("#home_page_form").node();
            pageForm.onsubmit = function() {
                pages.prepHomePageContentForSubmit()
            };
		}
	},
	
	/**
     * Attaches the necessary event handlers to the generated Folder Tree
     * to enable the folders be expanded or collapsed as necessary
     */
    attachFolderHandlers: function() {
        var dirTree = $p(".cms-page-list").node();
		
		if( dirTree == null ) {
			return;
		}
		
        var liNodes = dirTree.getElementsByTagName("li");
		
        for(var i = 0; i < liNodes.length; i++) {
            var node = liNodes.item(i);
			
            if( node.className.indexOf("folder") > -1 ) {
				
				node.title = "Click To Expand";
                node.onclick = function(e) {
					if(!e) e = window.event;
					
					var uls = this.getElementsByTagName("ul");
					if( uls.length > 0 ) {
						for(var x = 0; x < uls.length; x++) {
							var ul = uls.item(x);
							if( ul.parentNode == this ) { // only expand direct childNodes
								if( ul.style.display != "none" ) {
									$p(ul).hide();
								} else {
									$p(ul).show();
								}
							}
						}
					} else {
						var liItem = this;
						var query = "action=show_sub_pages&parent_id=" + this.getAttribute("data-id");
						$p.post( pages.ajax_page, query, function(data) {
							var ul = document.createElement("ul");
							ul.style.display = "none";
							ul.innerHTML = data;
							
							liItem.appendChild(ul);
							$p(ul).show();
							
							pages.attachFolderHandlers();
						});		
					}
                    
					
                    pages.stopEvent(e);
                }
            } else {
				
				node.onclick = function(e) {
					if(!e) e = window.event;
				
					pages.stopEvent(e);
				};	
			}
        }
		
		// once the folder handlers are created, bind the actions to the various
		// list item links
		pages.bindPageLinks();
    },
	
	/**
	 * Binds the event listener to the various links (Edit/Delete/Preview/Publish).
	 *
	 * This function uses the direct "element.onclick" since it is applied frequently
	 * and recursively, so as not to bind multiple action listeners to the various items
	 * that match the selectors
	 */ 
	bindPageLinks: function() {
		
		// add functionality to prevent bubbling of click events on the check boxes
		$p.all(".cms-page-list a, .cms-page-list input", function(el) {
			el.onclick = function(e) {
				pages.stopEvent(e);
			};
		});
		
		// add the event listener for all the publishing links available
		$p.all(".cms-publish-link, .cms-unpublish-link", function(el) {
			el.onclick = function(e) {
				if( el.className == 'cms-publish-link' ) {
					pages.publishPage('unpublish', this );
				} else {
					pages.publishPage('publish', this );
				}
				
				pages.stopEvent(e);
				return false;
			};
		});
		
		// Add an event listener to all the edit links since the folder handler
		// function will disable all the links by preventing bubbling
		$p.all(".cms-page-list .edit-link", function(el) {
			el.onclick = function(e) {
				
				var query = "action=load_page&page_id=" + this.getAttribute('data-id');
				$p.post( pages.ajax_page, query, function(data) {

					var obj = $p.parseJSON(data);
					
					console.log(obj);
					
					$p("#ParentID").val( obj.ParentID );
					$p("#PageName").val( obj.PageName );
					$p("#PagePosition").val( obj.PagePosition );
					$p("#PageNameAlias").val( obj.PageNameAlias );
					$p("#PageDescription").val( obj.PageDescription );
					$p("#PageSummary").val( obj.PageSummary );
					$p("#PageContent").val( obj.PageContent );
                    $p("#PageLayout").val( obj.PageLayout );
					$p("#RedirectURL").val( obj.RedirectURL );
					$p("#action").val( "update_page" );
					$p("#id").val( obj.id );
					
					// only set this if there is actually content
					if( obj.PageSummary ) {
						tinyMCE.get('PageSummary').setContent( obj.PageSummary );
					}
					
					if( obj.PageContent ) {
						if( obj.PageContentType == "html" ) {
							$p("#HTMLEditor").val( obj.PageContent );
							tinyMCE.get('HTMLContent').setContent( obj.PageContent );
							pages.$tabs.tabs('select',0);
							
						} else if( obj.PageContentType == "php" ) {
							file_utils.setEditorContent( obj.PageContent );
							pages.$tabs.tabs('select',1);
						}
					}
					
					$p("#PageAddForm #submit-btn").val("Update Page");
					
					$p(".newsTbl").css('display','none');
					$p(".editor-block").css('display','block');	
				});
				
				pages.stopEvent(e);
				return false;
			};
		});
		
		$p.all(".cms-page-list .preview-link",function(e){
			e.onclick = function(e) {
				window.open(this.href,'_blank');
				pages.stopEvent(e);
				return false;
			};
		});
		
		$p.all(".cms-page-list .delete-link",function(el){
			el.onclick = function(e) {
				var elem = this;
				
				$p.showDialog({
					title: 'Confirm Delete Of Page and Sub Pages',
					content: 'Deleting this page will potentially delete all sub pages as well.<br />'
							+ 'Do you want to continue the process?',
					
					okButtonText: "Delete Page(s)",
					okButtonAction: function() {
						var query = "action=delete_pages&ids=" + elem.getAttribute("data-id");
						$p.post("ajax_pages/pages.php", query, function(data) {
							$p("#page-li-" + elem.getAttribute("data-id")).remove();
						});
					}
				});
				
				pages.stopEvent(e);
				return false;
			};
		});
	},
	
	stopEvent: function (e) {
		if(!e) var e = window.event;
		
		//e.cancelBubble is supported by IE - this will kill the bubbling process.
		e.cancelBubble = true;
	
		//e.stopPropagation works W3C Compatible browsers.
		if (e.stopPropagation) {
			e.stopPropagation();
		}
		
		return false;
	},
	
	setSiteIdentifier: function(siteid) {
        pages.siteIdentifier = siteid;
    },

    getSiteIdentifier: function(siteid) {
        return pages.siteIdentifier;
    },
	
	setPageListExpanded: function(state) {
		pages.pageListExpanded = state;
	},
	
	/**
	 * Processes and saves the currently displayed page form depending on whether
	 * we are adding or updating pages
	 */
	processFormData: function() {
		try {
			tinyMCE.triggerSave();
		} catch(e) {}
		
		pages.prepContentForSubmit();
		var query = $p("#PageAddForm").serialize();
		
		$p.post( pages.ajax_page, query, function(data) {
			
			var action = $p("#action").val();
			// update the page name

			var pageName = $p("#PageAddForm #PageName").val();
			var position = $p("#PageAddForm #PagePosition").val();
			var new_parent_id = $p("#PageAddForm #ParentID").val();
			
			if( action == "update_page") {
				
				var pageData = $p.parseJSON(data);
	
				var id = pageData.id;
				var url = pageData.URL;

                $p(".cms-page-list a[data-id='" + id + "'].preview-link")
					.attr("href", url );
                    
				$p(".cms-page-list a[data-id='" + id + "'].page-name")
					.html(pageName)
					.attr("data-position", position);

                $p("#page-li-" + id).attr("data-position", position);
					
   				
				
				// attempt to move the page to a new parent its old parent has changed
				var old_parent_id = $(".cms-page-list #page-li-" + id).parent().parent().attr('data-id');

				if( new_parent_id != old_parent_id ) {
					
					var li = document.getElementById("page-li-" + id);
					
					if( new_parent_id != "" ) {	
						var new_parent = document.getElementById("page-li-" + new_parent_id);
						
						var p_uls = new_parent.getElementsByTagName("ul");
						
						// if the new parent has their child elements loaded, then
						// append this new child to the list of items
						if( p_uls != null && p_uls.length > 0  ) {
							p_uls[0].appendChild(li);
							pages.sortPages(p_uls[0]);
						} 
						
						// else simply remove it
						else {	
							li.parentNode.removeChild(li);
						}
					}
					
					// add the page to the root page list
					else {
						var page_list = document.getElementById("cms-page-list");
						page_list.appendChild(li);
						pages.sortPages(page_list);
					}
				} 
				
				else {
					var old_parent = document.getElementById("page-li-" + old_parent_id);
					var p_uls = old_parent.getElementsByTagName("ul");
					pages.sortPages(p_uls[0]);
				}
				
			}
			
			else if( action == "add_page" ) {
				// we simply use the returned page listing data to create a new node
				var tempNode = document.createElement("ul");
				tempNode.innerHTML = data;
				
				var li = tempNode.getElementsByTagName("li")[0];
				
				if( new_parent_id != "" ) {	
					var new_parent = document.getElementById("page-li-" + new_parent_id);
					
					var p_uls = new_parent.getElementsByTagName("ul");
					
					// if the new parent has their child elements loaded, then
					// append this new child to the list of items
					if( p_uls != null && p_uls.length > 0  ) {
						p_uls[0].appendChild(li);
						pages.sortPages(p_uls[0]);
					} 
					
					// else indicate the current page has new child items by making it a
					// folder with the necessary functionality
					else {	
						new_parent.className = "folder";
						pages.attachFolderHandlers();
					}
				} 
				
				// add the new page to the root page list
				else {
					var page_list = document.getElementById("cms-page-list");
					page_list.appendChild(li);
					pages.sortPages(page_list);
				}
				
				// ensure the new page added has the AJAX functionality
				pages.bindPageLinks();
			}
			
			$p(".newsTbl").css('display','table');
			$p(".editor-block").css('display','none');
			
			document.getElementById("PageAddForm").reset();
			
		});	
	},
	
	/**
	 * Prepares the page for submission by copying the required content based on the content
	 * type into the generalise Content field
	 */
    prepContentForSubmit: function() {

		var content = document.getElementById("Content");
		var contentType = document.getElementById("ContentType");

		if( pages.contentType == 'html' ) {
			content.value = tinyMCE.get('HTMLContent').getContent();
		} else if( pages.contentType == 'php' ) {
			content.value = file_utils.getEditorContent();
		} else {
			content.value = "";
		}

		// provide the selected content type for submission
		contentType.value = pages.contentType;
       
    },
	
	/**
	 * Prepares the page for submission by copying the required content based on the content
	 * type into the generalise Content field
	 */
    prepHomePageContentForSubmit: function() {

		var content = null;
		if( document.getElementById("SiteHomePageText") ) {
			content = document.getElementById("SiteHomePageText");
		} else {
			content = document.getElementById("SiteFooterText")	
		}
		//var contentType = document.getElementById("ContentType");

		if( pages.contentType == 'html' ) {
			content.value = tinyMCE.get('BlockContent').getContent();
		} else if( pages.contentType == 'php' ) {
			content.value = file_utils.getEditorContent();
		} else {
			content.value = "";
		}

		// provide the selected content type for submission
		//contentType.value = pages.contentType;
       
    },
	
	publishPage: function(action, linkEl) {
		var query = "action=" + action + "&id="	+ linkEl.id;
		
		$p.post('ajax_pages/pages.php', query, function(data) {
			
			if( action == "publish" ) {
				linkEl.className = 'cms-publish-link';	
				linkEl.title = 'Published (Click To Unpublish)';
				linkEl.onclick = function() {
					pages.publishPage('unpublish', this);
				}
			} else {
				linkEl.className = 'cms-unpublish-link';
				linkEl.title = 'Unpublished (Click To Publish Now)';
				linkEl.onclick = function() {
					pages.publishPage('publish', this);
				}
			}
		});	
		
	}	
};